/*
 * Action.c
 *
 *  Created on: 09.08.2011
 *      Author: sili
 */

#include "AALAction.h"
#include "AALItem.h"

static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("at.sili.aalsystem.model.AALAction"));

static int actionId = 0;

AALAction::AALAction(const ActionType _actionType, AALItem * _aalItem, const char * _message, int _timeToLive, Controller * _controller){
	this->type = _actionType;
	this->aalItem = _aalItem;
	this->timestamp = -1;
	this->timeToLive = _timeToLive;
	this->controller = _controller;
	this->message.clear();
	if(_message != NULL)
		this->message.append(_message);
	this->id = ++actionId;
	this->children.clear();
	this->doReload = false;
	this->state = inProgress;
	AAL_TRACE(logger,"Constructor for id:%ld type:%s aalItemId:%d", this->id, this->typeToString(), this->aalItem != NULL ? this->aalItem->getId():-1);
}

AALAction::~AALAction() {
	AAL_TRACE(logger,"Destructor for id:%ld type:%s aalItemId:%d", this->id, this->typeToString(), this->aalItem != NULL ? this->aalItem->getId():-1);
	while(this->children.size() > 0){
		AALAction * childAction = this->children.back();
		AAL_TRACE(logger,"Deleting child id:%ld type:%s aalItemId:%d", childAction->id, childAction->typeToString(), childAction->aalItem != NULL ? childAction->aalItem->getId():-1);
		this->children.pop_back();
		this->controller->discard(childAction);
		delete(childAction);
	}
}

bool AALAction::isAlive(){
	if(this->timeToLive > 0 && this->timestamp > -1){
		if(time(0) > this->timestamp + this->timeToLive){
			return false;
		} else {
			return true;
		}
	}
	return true;
}

void AALAction::resetTimeToLiveTimer(){
	this->timestamp = time(0);
}

const char * AALAction::typeToString(){
	switch (this->type){
		case doLog:
			return "doLog";
			break;
		case doShow:
			return "doShow";
			break;
		case doInfo:
			return "doInfo";
			break;
		case doWarn:
			return "doWarn";
			break;
		case doAlarm:
			return "doAlarm";
			break;
		case doHide:
			return "doHide";
			break;
		case doSetValue:
			return "doSetValue";
			break;
		case doTemplate:
			return "doTemplate";
			break;
		case doImport:
			return "doImport";
			break;
		case doPlayAudio:
			return "doPlayAudio";
			break;
		case doReaload:
			return "doReload";
			break;
		default:
			return "unknown.... ";
			break;
	}
}
